package com.css.fxfzfxqh.modules.util.hypergraph.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzfxqh.base.dict.repository.DictItemRepository;
import com.css.fxfzfxqh.base.dict.repository.entity.DictItemEntity;
import com.css.fxfzfxqh.base.response.RestResponse;
import com.css.fxfzfxqh.constants.YNEnum;
import com.css.fxfzfxqh.modules.lifelineEngineering.entity.EvaluationResults;
import com.css.fxfzfxqh.modules.lifelineEngineering.entity.LifelineTaskEntity;
import com.css.fxfzfxqh.modules.lifelineEngineering.repository.EstimateRepository;
import com.css.fxfzfxqh.modules.lifelineEngineering.repository.TaskManagementRepository;
import com.css.fxfzfxqh.modules.util.hypergraph.entity.NetworkanalystVersion;
import com.css.fxfzfxqh.modules.util.hypergraph.service.AsyncService;
import com.css.fxfzfxqh.modules.util.hypergraph.service.HypergraphService;
import com.css.fxfzfxqh.util.*;
import com.css.fxfzfxqh.zcpt.sys.entity.SUser;
import com.css.fxfzfxqh.zcpt.sys.service.SUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.*;

@Service
public class HypergraphServiceImpl implements HypergraphService {

    @Value("${hypergraph.iServerHttp}")
    String iServerHttp;
    @Value("${hypergraph.iServerHttp10i}")
    String iServerHttp10i;
    @Value("${hypergraph.userName}")
    String userName;
    @Value("${hypergraph.password}")
    String password;

    //    @Resource
//    RestTemplate restTemplate;
    RestTemplate restTemplate = getRestTemplate();

    @Value("${hypergraph.filePath}")
    String filePath;
    @Value("${hypergraph.mapsPath}")
    String mapsPath;

    @Autowired
    DictItemRepository dictItemRepository;
    @Autowired
    SUserService sUserService;
    @Resource
    JdbcTemplate jdbcTemplate;
    @Resource
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;
    @Autowired
    private TaskManagementRepository taskManagementRepository;
    @Autowired
    private EstimateRepository estimateRepository;
    @Resource
    AsyncService asyncService;

    /**
     * 调度器使用的RestTemplate，超时6000s
     * @return
     */
    public RestTemplate getRestTemplate(){
        RestTemplate restTemplate = new RestTemplateBuilder()
                .setConnectTimeout(Duration.ofSeconds(6000))
                .setReadTimeout(Duration.ofSeconds(6000))
                .build();
        //解决中文乱码
        List<HttpMessageConverter<?>> msgConv = restTemplate.getMessageConverters();
        if(msgConv != null && !msgConv.isEmpty()) {
            for(int i = 0; i < msgConv.size(); i++ ){
                if(msgConv.get(i).getClass().equals(StringHttpMessageConverter.class)) {
                    msgConv.set(i, new StringHttpMessageConverter(StandardCharsets.UTF_8));
                }
            }
        }
        return restTemplate;
    }

    /**
     * @param map layerName:
     *            type://类型
     *            WorkspaceReload//刷新指定超图工作空间数据源数据集
     *            exportShp//导出shp文件
     *            newWorkspaceNetwork//工作空间发布交通网络分析服务
     *            deleteWorkspace//删除超图工作空间服务
     * @return
     */
    @Override
    public RestResponse getServerToken(Map<String, Object> map) {
        RestResponse restResponse = null;
        try {
            String dataUrl = iServerHttp + "/iserver/services/security/tokens.rjson";
            String queryType = (String) map.get("type");
            if(queryType.equals("newWorkspaceNetwork") || queryType.equals("deleteWorkspace")){//10i试用版网络分析服务
                dataUrl = iServerHttp10i + "/iserver/services/security/tokens.rjson";
            }
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return RestResponse.fail(e.getMessage());
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //System.out.println(dataUrl);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userName", userName);
            jsonObject.put("password", password);
            jsonObject.put("clientType", "NONE");//查询数量
            jsonObject.put("expiration", 600);//申请令牌的有效期，从发布令牌的时间开始计算，单位为分钟
            //System.out.println(jsonObject);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(jsonObject, headers);
            ResponseEntity<String> exchange = restTemplate.exchange(dataUrl, HttpMethod.POST, entity, String.class);

            // result.put("result", exchange.getBody());

            String type = (String) map.get("type");
            String layerName = (String) map.get("layerName");
            if (type.equals("WorkspaceReload")) {
                String datasource = (String) map.get("datasource");//数据源
                String dataset = (String) map.get("dataset");//数据集
                //查询字典--超图数据源工作空间文件路径
                DictItemEntity dte = dictItemRepository.findOneByDictItemCodeAndDictId(datasource, "12");
                String smwuUrl = dte.getDictItemName();//工作空间文件路径
                //刷新指定超图工作空间数据源数据集
                restResponse = mapLayerWorkspaceReload(smwuUrl, datasource, dataset, exchange.getBody());
            } else if (type.equals("token")) {//获取超图服务token
                String token = exchange.getBody();
                restResponse = RestResponse.succeed(token);
            } else if (type.equals("exportShp")) {
                String sqlFilter = (String) map.get("sqlFilter");//过滤条件
                String timeStamp = (String) map.get("timeStamp");//时间戳，用于数据集导出名称后缀，防止重名
                String datasource = (String) map.get("datasource");//数据源fxfzfxqh
                //tif发布超图服务工具--创建任务（导出shp文件）
                restResponse = tifMapLayerToolJobPost(datasource, layerName, sqlFilter, timeStamp, exchange.getBody());
            } else if(type.equals("newWorkspaceNetwork")){//工作空间发布交通网络分析服务
                //工作空间发布交通网络分析服务
                restResponse = supermapPostWorkspace(map,exchange.getBody());
            } else if(type.equals("deleteWorkspace")){//删除超图工作空间服务
                NetworkanalystVersion networkanalystVersion = (NetworkanalystVersion) map.get("networkanalystVersion");
                //根据ID逻辑删除版本
                deleteNetworkanalystVersionById(networkanalystVersion.getId());
                //删除超图工作空间服务
                restResponse = supermapDeleteWorkspace(map,exchange.getBody());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail(e.getMessage());
        }
        return restResponse;
    }

    // tif发布超图服务工具--创建任务（导出shp文件）
    private RestResponse tifMapLayerToolJobPost(String datasource, String layerName,String sqlFilter,String timeStamp,String serverToken) {
        RestResponse restResponse = null;
        try {
            String dataUrl = iServerHttp + "/iserver/services/geoprocessing/restjsr/gp/v2/sps.WorkflowProcessFactory.models.tif发布:导出shp文件fxqh/jobs?token=" + serverToken;
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return RestResponse.fail(e.getMessage());
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //System.out.println(dataUrl);
            String resultFilePath = filePath + layerName + "_" + timeStamp + ".file";//导出文件路径
            //过滤条件
            String sql = "1=1";
            if (!PlatformObjectUtils.isEmpty(sqlFilter)) {
                sql = sqlFilter;
                //随机数
                String random1 = String.valueOf(Math.round(Math.random() * 10));
                String random2 = String.valueOf(Math.round(Math.random() * 10));
                String random3 = String.valueOf(Math.round(Math.random() * 10));
                resultFilePath = filePath + layerName + "_" + timeStamp + random1 + random2 + random3 + ".file";//导出文件路径
            }
            //执行处理自动化工具时的参数设置，形式为{”ParameterID1”:”value1”,”ParameterID2”:”value2”,……}，其中ParameterID为工具的参数ID，由对应的处理自动化工具描述可以确定，value为参数的值
            JSONObject jsonObject = new JSONObject();
            JSONObject parameter = new JSONObject();
            parameter.put("String_1", layerName);//数据集名称（表名）
            parameter.put("String_2", resultFilePath);//导出文件路径
            parameter.put("String_3", sql);//过滤条件
            jsonObject.put("parameter", parameter);
            JSONArray environment = new JSONArray();
            jsonObject.put("environment", environment);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(jsonObject, headers);
            ResponseEntity<JSONObject> exchange = restTemplate.exchange(dataUrl, HttpMethod.POST, entity, JSONObject.class);
            JSONObject body = exchange.getBody();
            if (body == null) {
                return RestResponse.fail("未获取到数据！");
            }
            // result.put("result", body.getString("jobID"));

            restResponse = tifMapLayerToolJobGet(body.getString("jobID"), serverToken);
            if (restResponse.getCode() == 200) {
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("dataset", layerName);
                jsonObject1.put("resultFilePath", resultFilePath);
                restResponse.setData(jsonObject1);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail(e.getMessage());
        }
        return restResponse;
    }

    private RestResponse tifMapLayerToolJobGet(String jobID, String serverToken) {
        JSONObject result = new JSONObject();
        try {
            String dataUrl = iServerHttp + "/iserver/services/geoprocessing/restjsr/gp/v2/jobs/" + jobID + ".json?token=" + serverToken;
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return RestResponse.fail(e.getMessage());
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //System.out.println(dataUrl);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(new JSONObject(), headers);
            ResponseEntity<JSONObject> exchange = restTemplate.exchange(dataUrl, HttpMethod.GET, entity, JSONObject.class);
            JSONObject body = exchange.getBody();
            if (body == null) {
                return RestResponse.fail("未获取到数据！");
            }
            if (!body.getJSONObject("state").getBooleanValue("success")
                    && !body.getJSONObject("state").getString("runState").equals("RUNNING")) {
                return RestResponse.fail("未获取到数据！");
            }
            BigDecimal percent = body.getJSONObject("progress").getBigDecimal("percent");
            while (percent.compareTo(BigDecimal.valueOf(100)) < 0) {
                Thread.sleep(500);
                //获取任务执行百分比
                percent = tifMapLayerToolJobGetPercent(jobID, serverToken);
                if (percent.compareTo(BigDecimal.valueOf(-1)) == 0) {
                    return RestResponse.fail("该任务未获取到数据！");
                }
            }
            result.put("result", "获取成功！");
        } catch (Exception e) {
            e.printStackTrace();
            if(e.getMessage().contains("无效的令牌")){
                return RestResponse.fail("无效的令牌！");
            }
            tifMapLayerToolJobGet(jobID, serverToken);
        }
        return RestResponse.succeed(result);
    }

    //获取任务执行百分比
    private BigDecimal tifMapLayerToolJobGetPercent(String jobID, String serverToken) {
        BigDecimal jobPercent = BigDecimal.ZERO;
        try {
            String dataUrl = iServerHttp + "/iserver/services/geoprocessing/restjsr/gp/v2/jobs/" + jobID + ".json?token=" + serverToken;
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return jobPercent;
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //System.out.println(dataUrl);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(new JSONObject(), headers);
            ResponseEntity<JSONObject> exchange = restTemplate.exchange(dataUrl, HttpMethod.GET, entity, JSONObject.class);
            JSONObject body = exchange.getBody();
            if (body == null) {
                return jobPercent;
            }
            if (!body.getJSONObject("state").getBooleanValue("success")
                    && !body.getJSONObject("state").getString("runState").equals("RUNNING")) {
                return BigDecimal.valueOf(-1);
            }
            BigDecimal percent = body.getJSONObject("progress").getBigDecimal("percent");
            if(percent.compareTo(BigDecimal.valueOf(100)) == 0){
                if(body.getJSONObject("state").getString("runState").equals("RUNNING")){//正在执行
                    percent = BigDecimal.valueOf(99);
                }
            }
            jobPercent = percent;
        } catch (Exception e) {
            e.printStackTrace();
            if(e.getMessage().contains("无效的令牌")){
                return BigDecimal.valueOf(-1);
            }
            return jobPercent;
        }
        return jobPercent;
    }

    //刷新指定超图工作空间数据源数据集
    private RestResponse mapLayerWorkspaceReload(String smwuUrl, String datasource, String dataset, String serverToken) {
        RestResponse restResponse = null;
        try {
            String dataUrl = iServerHttp + "/iserver/manager/workspaces/workspacereload.rjson?token=" + serverToken;
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return RestResponse.fail(e.getMessage());
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //刷新指定数据源数据集时的参数设置，形式为{"workspaceConnectionInfo":"C:/Users/lenovo/Desktop/192/MapData/fxfzfxqh/fxfzdzzh10/fxfzfxqh.smwu","isForce":true,"datasets":{"fxfzfxqh":["dzzh_slide_result_intensity"]}}
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("workspaceConnectionInfo", smwuUrl);
            jsonObject.put("isForce", true);
            JSONObject datasets = new JSONObject();
            JSONArray datasetArray = new JSONArray();
            datasetArray.add(dataset);
            datasets.put(datasource, datasetArray);//数据源数据集名称
            jsonObject.put("datasets", datasets);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(jsonObject, headers);
            ResponseEntity<String> exchange1 = restTemplate.exchange(dataUrl, HttpMethod.POST, entity, String.class);
//            ResponseEntity<JSONObject> exchange = restTemplate.exchange(dataUrl, HttpMethod.POST, entity, JSONObject.class);
            JSONObject body = JSON.parseObject(exchange1.getBody());
            if (body == null) {
                return RestResponse.fail("未获取到数据！");
            }
            if (body.getBooleanValue("succeed")) {
                restResponse = RestResponse.succeed("刷新成功");
            } else {
                restResponse = RestResponse.fail("刷新失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail(e.getMessage());
        }
        return restResponse;
    }

    //刷新指定超图工作空间数据源数据集
    @Override
    public boolean getWorkspaceReload(String dataset) {
        boolean bool = false;
        Map<String, Object> map = new HashMap<>();
        map.put("type", "WorkspaceReload");
        map.put("datasource", "fxfzfxqh");//数据源（数据库名）
        map.put("dataset", dataset);//数据集（表名）
        RestResponse restResponse1 = getServerToken(map);//刷新指定超图工作空间数据源数据集
        if (restResponse1.getCode() == 200) {
            //刷新成功
            bool = true;
        }

        return bool;
    }

    //获取超图服务token
    @Override
    public String getToken() {
        Map<String, Object> map = new HashMap<>();
        map.put("type", "token");
        RestResponse restResponse = getServerToken(map);
        String token = (String) restResponse.getData();

        return token;
    }

    //SQL查询超图图层数据
    @Override
    public RestResponse mapSqlQueryResultsPost(String layerUrl, String datasource, String dataset, String networkType, String sqlFilter) {
        RestResponse restResponse = null;
        try {
//            String dataUrl = iServerHttp + "/iserver/services/map-changchun/rest/maps/长春市区图/queryResults.json?returnContent=true";
//            String dataUrl = "http://10.7.208.233:8080/iserver/services/map-changchun/rest/maps/长春市区图/queryResults.json?returnContent=true";
//            String dataUrl = "http://10.7.208.233:8080/iserver/services/map-dxPipeNetwork/rest/maps/dxPipeNetwork_Network@dxPipeNetwork/queryResults.json?returnContent=true";
//            String dataUrl = "http://10.13.155.192:8090/iserver/services/map-smxNetwork/rest/maps/DataSource_Network@DataSource/queryResults.json?returnContent=true";
            String dataUrl = layerUrl + "/queryResults.json?returnContent=true";
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return RestResponse.fail(e.getMessage());
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //System.out.println(dataUrl);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("queryMode", "SqlQuery");
            JSONObject queryParameters = new JSONObject();
            queryParameters.put("expectCount", 100000);
            queryParameters.put("networkType", networkType);//LINE、POINT、REGION
            queryParameters.put("queryOption", "ATTRIBUTEANDGEOMETRY");//查询结果类型枚举，描述查询结果返回类型，包括ATTRIBUTE 只返回属性、GEOMETRY 只返回几何实体、ATTRIBUTEANDGEOMETRY 返回属性和几何实体。
            JSONArray queryParams = new JSONArray();
            JSONObject params = new JSONObject();
            params.put("name", dataset+"@"+datasource);
            params.put("attributeFilter", sqlFilter);
            queryParams.add(params);
            queryParameters.put("queryParams", queryParams);
            jsonObject.put("queryParameters", queryParameters);
            System.out.println(jsonObject);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(jsonObject, headers);
            ResponseEntity<JSONObject> exchange = restTemplate.exchange(dataUrl, HttpMethod.POST, entity, JSONObject.class);
            JSONObject body = exchange.getBody();
            if (body == null) {
                return RestResponse.fail("未获取到数据！");
            }
            int currentCount = body.getInteger("currentCount");
            int totalCount = body.getInteger("totalCount");
            if(currentCount>0){//返回结果
                JSONArray recordsets = body.getJSONArray("recordsets");
//            JSONArray features = body.getJSONArray("recordsets").getJSONObject(0).getJSONArray("features");
                JSONObject result = new JSONObject();
                result.put("currentCount",currentCount);
                result.put("totalCount",totalCount);
                result.put("recordsets",recordsets);
                restResponse = RestResponse.succeed(result);
            }else{
                return RestResponse.fail("无查询结果数据！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail(e.getMessage());
        }
        return restResponse;
    }

    //下游追踪
    @Override
    public RestResponse networkTracedown(String layerUrl, String nodeID, String edgeID, boolean isUncertainDirectionValid, boolean returnFeatures) {
        JSONObject result = new JSONObject();
        try {
//            String dataUrl = iServerHttp + "/iserver/services/transportationanalyst-sample/rest/networkanalyst/RoadNet@Changchun/tracedown.json?weightName=&isUncertainDirectionValid=true&returnFeatures=true&edgeID=101";
//            String dataUrl = "http://10.7.208.233:8080/iserver/services/transportationanalyst-sample/rest/networkanalyst/RoadNet@Changchun/tracedown.json?weightName=&isUncertainDirectionValid=true&returnFeatures=true&edgeID=101";
//            String dataUrl = layerUrl + "/iserver/services/transportationanalyst-sample/rest/networkanalyst/RoadNet@Changchun/tracedown.json?weightName=&isUncertainDirectionValid=true&returnFeatures=true&edgeID=101";
//            String dataUrl = "http://10.7.208.233:8080/iserver/services/transportationAnalyst-dxPipeNetwork/rest/networkanalyst/dxPipeNetwork_Network@dxPipeNetwork/tracedown.json?weightName=";
            String dataUrl = layerUrl + "/tracedown.json?weightName=";
            dataUrl += "&isUncertainDirectionValid="+isUncertainDirectionValid;//指定不确定流向是否有效。true表示不确定流向有效，遇到不确定流向时分析继续进行；false表示不确定流向无效，遇到不确定流向将停止在该方向上继续查找。
            dataUrl += "&returnFeatures="+returnFeatures;//是否返回结果要素的详细描述信息。若为 false，只返回结果要素的 ID 集合。
            if (PlatformObjectUtils.isNotEmpty(nodeID)) {
                dataUrl += "&nodeID="+nodeID;
            }
            if (PlatformObjectUtils.isNotEmpty(edgeID)) {
                dataUrl += "&edgeID="+edgeID;
            }
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return RestResponse.fail(e.getMessage());
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //System.out.println(dataUrl);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(new JSONObject(), headers);
            ResponseEntity<JSONObject> exchange = restTemplate.exchange(dataUrl, HttpMethod.GET, entity, JSONObject.class);
            JSONObject body = exchange.getBody();
            if (body == null) {
                return RestResponse.fail("未获取到数据！");
            }
//            JSONArray nodes = body.getJSONArray("nodes");
//            JSONArray nodesFeatures = body.getJSONArray("nodesFeatures");
//            JSONArray edges = body.getJSONArray("edges");
//            JSONArray edgesFeatures = body.getJSONArray("edgesFeatures");
            result = body;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RestResponse.succeed(result);
    }

    //上游追踪
    @Override
    public RestResponse networkTraceup(String layerUrl, String nodeID, String edgeID, boolean isUncertainDirectionValid, boolean returnFeatures) {
        JSONObject result = new JSONObject();
        try {
//            String dataUrl = iServerHttp + "/iserver/services/transportationanalyst-sample/rest/networkanalyst/RoadNet@Changchun/traceup.json?weightName=&isUncertainDirectionValid=true&returnFeatures=true&edgeID=101";
//            String dataUrl = "http://10.7.208.233:8080/iserver/services/transportationanalyst-sample/rest/networkanalyst/RoadNet@Changchun/traceup.json?weightName=&isUncertainDirectionValid=true&returnFeatures=true&edgeID=101";
//            String dataUrl = layerUrl + "/iserver/services/transportationanalyst-sample/rest/networkanalyst/RoadNet@Changchun/traceup.json?weightName=&isUncertainDirectionValid=true&returnFeatures=true&edgeID=101";
//            String dataUrl = "http://10.7.208.233:8080/iserver/services/transportationAnalyst-dxPipeNetwork/rest/networkanalyst/dxPipeNetwork_Network@dxPipeNetwork/traceup.json?weightName=";
            String dataUrl = layerUrl + "/traceup.json?weightName=";
            dataUrl += "&isUncertainDirectionValid="+isUncertainDirectionValid;//指定不确定流向是否有效。true表示不确定流向有效，遇到不确定流向时分析继续进行；false表示不确定流向无效，遇到不确定流向将停止在该方向上继续查找。
            dataUrl += "&returnFeatures="+returnFeatures;//是否返回结果要素的详细描述信息。若为 false，只返回结果要素的 ID 集合。
            if (PlatformObjectUtils.isNotEmpty(nodeID)) {
                dataUrl += "&nodeID="+nodeID;
            }
            if (PlatformObjectUtils.isNotEmpty(edgeID)) {
                dataUrl += "&edgeID="+edgeID;
            }
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return RestResponse.fail(e.getMessage());
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //System.out.println(dataUrl);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(new JSONObject(), headers);
            ResponseEntity<JSONObject> exchange = restTemplate.exchange(dataUrl, HttpMethod.GET, entity, JSONObject.class);
            JSONObject body = exchange.getBody();
            if (body == null) {
                return RestResponse.fail("未获取到数据！");
            }
//            JSONArray nodes = body.getJSONArray("nodes");
//            JSONArray nodesFeatures = body.getJSONArray("nodesFeatures");
//            JSONArray edges = body.getJSONArray("edges");
//            JSONArray edgesFeatures = body.getJSONArray("edgesFeatures");
            result = body;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RestResponse.succeed(result);
    }

    //爆管分析
    @Override
    public RestResponse networkBurstanalyse(String layerUrl, String sourceNodeIDs, String nodeID, String edgeID, boolean isUncertainDirectionValid, boolean returnFeatures) {
        JSONObject result = new JSONObject();
        try {
//            String dataUrl = "http://10.7.208.233:8080/iserver/services/transportationAnalyst-dxPipeNetwork/rest/networkanalyst/dxPipeNetwork_Network@dxPipeNetwork/burstanalyse.json?";
            String dataUrl = layerUrl + "/burstanalyse.json?isUncertainDirectionValid=";
            dataUrl += isUncertainDirectionValid;//指定不确定流向是否有效。true表示不确定流向有效，遇到不确定流向时分析继续进行；false表示不确定流向无效，遇到不确定流向将停止在该方向上继续查找。
            dataUrl += "&returnFeatures="+returnFeatures;//是否返回结果要素的详细描述信息。若为 false，只返回结果要素的 ID 集合。
            if (PlatformObjectUtils.isNotEmpty(sourceNodeIDs)) {
                dataUrl += "&sourceNodeIDs="+sourceNodeIDs;
            }
            if (PlatformObjectUtils.isNotEmpty(nodeID)) {
                dataUrl += "&nodeID="+nodeID;
            }
            if (PlatformObjectUtils.isNotEmpty(edgeID)) {
                dataUrl += "&edgeID="+edgeID;
            }
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return RestResponse.fail(e.getMessage());
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //System.out.println(dataUrl);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(new JSONObject(), headers);
            ResponseEntity<JSONObject> exchange = restTemplate.exchange(dataUrl, HttpMethod.GET, entity, JSONObject.class);
            JSONObject body = exchange.getBody();
            if (body == null) {
                return RestResponse.fail("未获取到数据！");
            }
//            JSONArray criticalNodes = body.getJSONArray("criticalNodes");
//            JSONArray normalNodes = body.getJSONArray("normalNodes");
//            JSONArray edges = body.getJSONArray("edges");
            result = body;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RestResponse.succeed(result);
    }

    //连通性分析
    @Override
    public RestResponse networkConnectededges(String layerUrl, String nodeIDs, String edgeIDs, boolean connected, boolean returnFeatures) {
        JSONObject result = new JSONObject();
        try {
//            String dataUrl = "http://10.7.208.233:8080/iserver/services/transportationAnalyst-dxPipeNetwork/rest/networkanalyst/dxPipeNetwork_Network@dxPipeNetwork/connectededges.json?";
            String dataUrl = layerUrl + "/connectededges.json?connected=";
            dataUrl += connected;//指定不确定流向是否有效。true表示不确定流向有效，遇到不确定流向时分析继续进行；false表示不确定流向无效，遇到不确定流向将停止在该方向上继续查找。
            dataUrl += "&returnFeatures="+returnFeatures;//是否返回结果要素的详细描述信息。若为 false，只返回结果要素的 ID 集合。
            if (PlatformObjectUtils.isNotEmpty(nodeIDs)) {
                dataUrl += "&nodeIDs="+nodeIDs;
            }
            if (PlatformObjectUtils.isNotEmpty(edgeIDs)) {
                dataUrl += "&edgeIDs="+edgeIDs;
            }
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return RestResponse.fail(e.getMessage());
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //System.out.println(dataUrl);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(new JSONObject(), headers);
            ResponseEntity<JSONObject> exchange = restTemplate.exchange(dataUrl, HttpMethod.GET, entity, JSONObject.class);
            JSONObject body = exchange.getBody();
            if (body == null) {
                return RestResponse.fail("未获取到数据！");
            }
//            JSONArray nodes = body.getJSONArray("nodes");
//            JSONArray nodesFeatures = body.getJSONArray("nodesFeatures");
//            JSONArray edges = body.getJSONArray("edges");
//            JSONArray edgesFeatures = body.getJSONArray("edgesFeatures");
            result = body;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RestResponse.succeed(result);
    }

    //工作空间发布交通网络分析服务
    private RestResponse supermapPostWorkspace(Map<String, Object> map, String serverToken) {
        RestResponse restResponse = null;
        try {
            NetworkanalystVersion networkanalystVersion = (NetworkanalystVersion) map.get("networkanalystVersion");
            String smwuUrl = networkanalystVersion.getSmwuUrl();//工作空间路径
            String udbxUrl = networkanalystVersion.getUdbxUrl();//工作空间路径
            String datasource = networkanalystVersion.getDatasource();//数据源名称
            String dataset = networkanalystVersion.getDataset();//工作空间内的网络数据集名称
            if (PlatformObjectUtils.isEmpty(smwuUrl) || PlatformObjectUtils.isEmpty(udbxUrl) || PlatformObjectUtils.isEmpty(datasource) || PlatformObjectUtils.isEmpty(dataset)){
                return RestResponse.fail("缺少超图工作空间文件参数");
            }
            //发布工作空间
//            String dataUrl = iServerHttp + "/iserver/manager/workspaces.rjson?token=" + serverToken;
            String dataUrl = iServerHttp10i + "/iserver/manager/workspaces.rjson?token=" + serverToken;//10i试用版网络分析服务
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return RestResponse.fail(e.getMessage());
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //System.out.println(dataUrl);

            JSONObject parameter = new JSONObject();
            parameter.put("workspaceConnectionInfo", smwuUrl);//工作空间路径或者数据库的连接信息
            JSONArray servicesTypes = new JSONArray();
            //地图服务
            servicesTypes.add("RESTMAP");//地图服务
            parameter.put("mapEditable", true);
            parameter.put("mapDpi", 96);
            //交通网络分析服务
            servicesTypes.add("RESTTRANSPORTATIONANALYST");//交通网络分析服务
            parameter.put("servicesTypes", servicesTypes);//发布的服务类型
            parameter.put("isMultiInstance", false);//是否启用多实例
            parameter.put("instanceCount", "");
            JSONObject transportationAnalystSetting = new JSONObject();
            JSONArray weightFieldInfos = new JSONArray();
            JSONObject weightFieldInfo = new JSONObject();
            weightFieldInfo.put("backWeightField", "SmLength");
            weightFieldInfo.put("forwardWeightField", "SmLength");
            weightFieldInfo.put("name", "SmLength");
            weightFieldInfos.add(weightFieldInfo);//权值字段信息集合，必设参数。
            transportationAnalystSetting.put("weightFieldInfos", weightFieldInfos);
            transportationAnalystSetting.put("workspaceConnectString", smwuUrl);
            transportationAnalystSetting.put("datasourceName", datasource);
            transportationAnalystSetting.put("datasetName", dataset);
            transportationAnalystSetting.put("nodeIDField", "SmNodeID");
            transportationAnalystSetting.put("edgeIDField", "SmEdgeID");
            transportationAnalystSetting.put("fromNodeIDField", "SmFNode");
            transportationAnalystSetting.put("toNodeIDField", "SmTNode");
            transportationAnalystSetting.put("initFacilityAnalyst", true);//开启设施网络分析
            transportationAnalystSetting.put("directionField", "Direction");//流向字段
            parameter.put("transportationAnalystSetting", transportationAnalystSetting);//发布交通网络分析服务的环境配置类。

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(parameter, headers);
            ResponseEntity<String> exchange = restTemplate.exchange(dataUrl, HttpMethod.POST, entity, String.class);
            JSONArray bodyArray = JSON.parseArray(JSON.parseObject(JSON.toJSONString(exchange)).getString("body"));
            if (bodyArray == null) {
                return RestResponse.fail("未获取到数据！");
            }
            for(int i=0;i<bodyArray.size();i++){
                JSONObject body = bodyArray.getJSONObject(i);
                String serviceAddress = body.getString("serviceAddress");
                String serviceType = body.getString("serviceType");
                if (PlatformObjectUtils.isNotEmpty(serviceAddress) && PlatformObjectUtils.isNotEmpty(serviceType) && serviceType.equals("RESTTRANSPORTATIONANALYST")){
                    networkanalystVersion.setId(UUIDGenerator.getUUID());
                    String networkUrl = serviceAddress + "/networkanalyst/"+dataset+"@"+datasource;
                    networkanalystVersion.setNetworkUrl(networkUrl);
                    //获取新的交通网络分析服务版本号
                    String version = getNetworkanalystVersionCode();
                    networkanalystVersion.setVersion(version);
                    networkanalystVersion.setDelFlag(YNEnum.N.toString());
                    networkanalystVersion.setCreateUser(PlatformSessionUtils.getUserId());
                    String userJson = sUserService.getSUser(PlatformSessionUtils.getUserId());
                    SUser sUser = CreateGson.createGson().fromJson(userJson, SUser.class);
                    String userName = sUser.getUserName();
                    networkanalystVersion.setCreateUserName(userName);
                    networkanalystVersion.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
                    //保存交通网络分析服务版本信息
                    saveNetworkanalystVersion(networkanalystVersion);
                    restResponse = RestResponse.succeed("发布成功！");
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail(e.getMessage());
        }
        return restResponse;
    }

    //获取新的交通网络分析服务版本号
    @Override
    public String getNetworkanalystVersionCode() {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        String date = df.format(new Date());
        String version = date+"SSWL";//设施网络分析
        int count = 0;
        try{
            SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
            String date1 = df1.format(new Date());
            String sql = "select count(*) from sys_networkanalyst_version where version like '%LJGH%' and cast(create_time as varchar) like '%"+date1+"%'";
            count = jdbcTemplate.queryForObject(sql,  Integer.class);
        }catch (Exception e){
            count = 0;
        }
        count++;
        if(count<10){
            version += "000" + count;
        }else if(count<100){
            version += "00" + count;
        }else if(count<1000){
            version += "0" + count;
        }else{
            version += count;
        }
        return version;
    }

    //保存交通网络分析服务版本信息
    public int saveNetworkanalystVersion(NetworkanalystVersion networkanalystVersion){
        String sql = "insert into sys_networkanalyst_version " +
                "(id,smwu_url,udbx_url,datasource,dataset,network_url," +
                "del_flag,create_user,create_user_name,create_time,attach_ids,task_id,direction_field," +
                "data_type,select_version1,select_version2,select_version3,version,remark) " +
                "values (:id,:smwuUrl,:udbxUrl,:datasource,:dataset,:networkUrl," +
                ":delFlag,:createUser,:createUserName,:createTime,:attachIds,:taskId,:directionField," +
                ":dataType,:selectVersion1,:selectVersion2,:selectVersion3,:version,:remark)";
        BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(networkanalystVersion);
        return namedParameterJdbcTemplate.update(sql, source);
    }

    //根据ID逻辑删除版本
    public boolean deleteNetworkanalystVersionById(String id){
        try{
            String sql = "update sys_networkanalyst_version set del_flag ='" + YNEnum.Y.toString() + "' where id='"+id+"'";
            jdbcTemplate.update(sql);

            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    //工作空间发布交通网络分析服务
    @Override
    public RestResponse newWorkspaceNetworkVersion(NetworkanalystVersion networkanalystVersion) {
        Map<String, Object> map = new HashMap<>();
        map.put("type", "newWorkspaceNetwork");
        map.put("networkanalystVersion", networkanalystVersion);
//        map.put("smwuUrl","E:/MapData/testfilenetwork/testfilenetwork/testfilenetwork.smwu");//工作空间路径
//        map.put("udbxUrl","E:/MapData/testfilenetwork/testfilenetwork/filenetwork.udbx");//工作空间数据源文件路径
//        map.put("datasource","filenetwork");//数据源名称
//        map.put("dataset","filenetwork_Network");//工作空间内的网络数据集名称
        return getServerToken(map);//工作空间发布交通网络分析服务
    }

    //根据任务ID查询交通网络分析服务版本信息
    @Override
    public NetworkanalystVersion getNetworkVersionByTaskId(String taskId){
        NetworkanalystVersion networkanalystVersion = null;
        try {
            String sql = "select * from sys_networkanalyst_version where task_id='"+taskId+"' and del_flag='0'";
            networkanalystVersion = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(NetworkanalystVersion.class));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return networkanalystVersion;
    }

    //根据ID查询交通网络分析服务版本信息
    @Override
    public NetworkanalystVersion getNetworkVersionById(String id){
        NetworkanalystVersion networkanalystVersion = null;
        try {
            String sql = "select * from sys_networkanalyst_version where id='"+id+"'";
            networkanalystVersion = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(NetworkanalystVersion.class));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return networkanalystVersion;
    }

    //查询交通网络分析服务版本列表
    @Override
    public RestResponse getNetworkVersionList(NetworkanalystVersion networkanalystVersion){
        try {
            String taskId = networkanalystVersion.getTaskId();
            String dataType = networkanalystVersion.getDataType();
            String version = networkanalystVersion.getVersion();
            String sql = "select * from sys_networkanalyst_version " +
                    "where version like '%SSWL%' and  data_type='"+dataType+"' and del_flag ='"+YNEnum.N.toString()+"'";
            if (PlatformObjectUtils.isNotEmpty(version)){
                sql += " and version like '%"+version+"%'";
            }
            if (PlatformObjectUtils.isNotEmpty(taskId)){
                sql += " and task_id ='"+taskId+"'";
            }
            sql += " order by create_time desc";
            Integer total = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(NetworkanalystVersion.class)).size();
            int curPage = networkanalystVersion.getCurPage();
            int pageSize = networkanalystVersion.getPageSize();
            int firstIndex = (curPage-1) * pageSize;
            int lastIndex = pageSize;
            StringBuilder limitSql = new StringBuilder(" limit "+lastIndex+" offset "+ firstIndex);
            sql += limitSql;
            List<NetworkanalystVersion> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(NetworkanalystVersion.class));
            Map<String, Object> map = new HashMap();
            map.put("total", total);
            map.put("rows", list);
            return RestResponse.succeed(map);
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail(e.getMessage());
        }
    }

    //批量逻辑删除交通网络分析服务版本信息
    @Override
    public RestResponse deleteNetworkanalystVersion(String idsStr){
        try{
            List<String> ids = new ArrayList<>();
            if (PlatformObjectUtils.isEmpty(ids)) {
                String[] idArr = idsStr.split(",");
                for(int i=0;i<idArr.length;i++){
                    String id = idArr[i];
                    //根据ID查询交通网络分析服务版本信息
                    NetworkanalystVersion networkanalystVersion = getNetworkVersionById(id);
                    //删除超图工作空间服务并逻辑删除版本
                    deleteWorkspace(networkanalystVersion);
                }
            }
            return RestResponse.succeed("删除成功");
        }catch (Exception e){
            e.printStackTrace();
            return RestResponse.fail(e.getMessage());
        }
    }

    //根据任务ID逻辑删除交通网络分析服务版本信息
    @Override
    public RestResponse deleteNetworkanalystVersionByTaskId(String taskId){
        try{
            //根据ID查询交通网络分析服务版本信息
            NetworkanalystVersion networkanalystVersion = getNetworkVersionByTaskId(taskId);
            if(networkanalystVersion!=null){
                //删除超图工作空间服务并逻辑删除版本
                deleteWorkspace(networkanalystVersion);
            }
            return RestResponse.succeed("删除成功");
        }catch (Exception e){
            e.printStackTrace();
            return RestResponse.fail(e.getMessage());
        }
    }

    //删除超图工作空间服务并逻辑删除版本
    public boolean deleteWorkspace(NetworkanalystVersion networkanalystVersion) {
        boolean bool = false;
        if(networkanalystVersion!=null){
            Map<String, Object> map = new HashMap<>();
            map.put("type", "deleteWorkspace");
            map.put("networkanalystVersion", networkanalystVersion);
            RestResponse res = getServerToken(map);
            if(res.getCode()==200){
                bool = true;
            }
        }
        return bool;
    }

    //删除超图工作空间服务
    private RestResponse supermapDeleteWorkspace(Map<String, Object> map, String serverToken) {
        RestResponse restResponse = null;
        try {
            NetworkanalystVersion networkanalystVersion = (NetworkanalystVersion) map.get("networkanalystVersion");
            String smwuUrl = networkanalystVersion.getSmwuUrl();//工作空间路径
            String udbxUrl = networkanalystVersion.getUdbxUrl();//工作空间路径
            if (PlatformObjectUtils.isEmpty(smwuUrl)){
                return RestResponse.fail("缺少超图工作空间文件参数");
            }
            //删除工作空间服务
//            String dataUrl = iServerHttp + "/iserver/manager/workspaces.rjson?token=" + serverToken;
            String dataUrl = iServerHttp10i + "/iserver/manager/workspaces.rjson?token=" + serverToken;//10i试用版网络分析服务
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return RestResponse.fail(e.getMessage());
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //System.out.println(dataUrl);

            JSONObject parameter = new JSONObject();
            parameter.put("workspaceConnectionInfo", smwuUrl);//工作空间路径或者数据库的连接信息

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(parameter, headers);
            ResponseEntity<String> exchange = restTemplate.exchange(dataUrl, HttpMethod.PUT, entity, String.class);
            JSONObject body = JSON.parseObject(JSON.parseObject(JSON.toJSONString(exchange)).getString("body"));
            if (body == null) {
                return RestResponse.fail("未获取到数据！");
            }
            boolean bool = body.getBoolean("succeed");
            if (bool){
                restResponse = RestResponse.succeed("删除超图工作空间服务成功！");
            }else{
                restResponse = RestResponse.succeed("删除超图工作空间服务失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail(e.getMessage());
        }
        return restResponse;
    }

    //导出shp文件
    public String exportShpFile(String datasource,String dataset,String sqlFilter,String timeStamp) {
        String resultFilePath = "";
        Map<String, Object> map = new HashMap<>();
        map.put("type", "exportShp");
        map.put("layerName", dataset);//数据集（表名）
        map.put("sqlFilter", sqlFilter);//过滤条件
        map.put("timeStamp", timeStamp);//时间戳，用于数据集名称后缀，防止重名
        map.put("datasource", datasource);//数据源fxfzfxqh
        RestResponse restResponse1 = getServerToken(map);//导出shp文件
        if (restResponse1.getCode() == 200) {
            //导出成功
            JSONObject json = (JSONObject) JSON.toJSON(restResponse1.getData());
            resultFilePath = (String)json.get("resultFilePath");
        }

        return resultFilePath;
    }

    //网络拓扑计算功能失效等级
    @Override
    public RestResponse countNetworkanalyst(NetworkanalystVersion networkanalystVersion){
        try {
            if(networkanalystVersion!=null){
                String taskId = networkanalystVersion.getTaskId();
                String dataType = networkanalystVersion.getDataType();//类型：供水系统、供气系统、供电系统、交通系统、通信系统
                String networkUrl = networkanalystVersion.getNetworkUrl();//交通网络分析服务路径
                String datasource = networkanalystVersion.getDatasource();
                String dataset = networkanalystVersion.getDataset();
                if (PlatformObjectUtils.isNotEmpty(networkUrl) && PlatformObjectUtils.isNotEmpty(datasource) && PlatformObjectUtils.isNotEmpty(dataset)
                    && networkUrl.contains("transportationAnalyst-") && networkUrl.contains("rest/networkanalyst")) {
                    //有网络分析服务
                }else{
                    return RestResponse.fail("请先导入网络拓扑数据");
                }
                //获取网络分析地图服务url
                String networkMapUrl = networkUrl.replace("transportationAnalyst-","map-");
                networkMapUrl = networkMapUrl.replace("rest/networkanalyst","rest/maps");
                //根据交通网络分析服务计算连通性分析，根据计算结果更新功能失效等级
                //查询全部节点要素信息列表
                JSONArray allNodeFeatures = getAllFeaturesByNetworkType(networkMapUrl,datasource,dataset,"POINT");
                //查询全部弧段要素信息列表
                JSONArray allEdgeFeatures = getAllFeaturesByNetworkType(networkMapUrl,datasource,dataset,"LINE");
                //地震输入方式的全部无效的节点ID列表
                List<List<String>> notValidNetworkNodeIdArrayList = new ArrayList<>();
                //地震输入方式的全部无效的弧段ID列表
                List<List<String>> notValidNetworkEdgeIdArrayList = new ArrayList<>();
                //地震输入方式的全部节点ID是否有效列表
                List<JSONObject> allNetworkNodeIdValidObjList = new ArrayList<>();
                //地震输入方式的全部弧段ID是否有效列表
                List<JSONObject> allNetworkEdgeIdValidObjList = new ArrayList<>();
                //地震输入方式的全部节点ID对应的主键id
                JSONObject allNetworkNodeIdObj = new JSONObject();
                if(allNodeFeatures!=null && allNodeFeatures.size()>0){
                    for(int i=0;i<allNodeFeatures.size();i++){
                        JSONObject nodeFeature = allNodeFeatures.getJSONObject(i);
                        String nodeID = nodeFeature.getString("ID");
                        JSONArray nodeFieldNames = nodeFeature.getJSONArray("fieldNames");
                        JSONArray nodeFieldValues = nodeFeature.getJSONArray("fieldValues");
                        //主键ID
                        String id = getFieldValueByName(nodeFieldNames,nodeFieldValues,"id");//根据字段名称获取数据
                        allNetworkNodeIdObj.put(nodeID,id);
                    }
                }
                //地震输入方式的全部弧段ID对应的主键id
                JSONObject allNetworkEdgeIdObj = new JSONObject();
                if(allEdgeFeatures!=null && allEdgeFeatures.size()>0){
                    for(int i=0;i<allEdgeFeatures.size();i++){
                        JSONObject edgeFeature = allEdgeFeatures.getJSONObject(i);
                        String edgeID = edgeFeature.getString("ID");
                        JSONArray edgeFieldNames = edgeFeature.getJSONArray("fieldNames");
                        JSONArray edgeFieldValues = edgeFeature.getJSONArray("fieldValues");
                        //主键ID
                        String id = getFieldValueByName(edgeFieldNames,edgeFieldValues,"id");//根据字段名称获取数据
                        allNetworkEdgeIdObj.put(edgeID,id);
                    }
                }
                //当前任务
                String userId = PlatformSessionUtils.getUserId();
                LifelineTaskEntity taskEntity = taskManagementRepository.getCurrentTask(userId);
                //点数据列表
                List<EvaluationResults> pointList = estimateRepository.getListByTaskId(taskEntity.getId());
                //线数据列表
                List<EvaluationResults> lineList = estimateRepository.getLineListByTaskId(taskEntity.getId());
                //输入方式(1设定烈度,2 设定地震影响场)
                int inputMethod = taskEntity.getInputMethod();
                //地震输入方式列表
                List<String> typeList = new ArrayList<>();
                if(inputMethod==1){
                    typeList.add("烈度6");
                    typeList.add("烈度7");
                    typeList.add("烈度8");
                    typeList.add("烈度9");
                    typeList.add("烈度10");
                }else{
                    typeList.add("地震影响场");
                }
                //判断网络分析服务是否为当前任务破坏等级分析，即判断主键ID是否存在一致
                boolean pointIdBool = getIdBoolByType(allNodeFeatures,pointList);
                boolean lineIdBool = getIdBoolByType(allEdgeFeatures,lineList);
                if(pointIdBool==false && lineIdBool==false){
                    return RestResponse.fail("网络拓扑数据与破坏等级分析数据不一致，请重新导入网络拓扑数据！");
                }
                for(int i=0;i<typeList.size();i++){
                    //全部节点ID是否有效
                    JSONObject allNetworkNodeIdValidObj = new JSONObject();
                    //全部弧段ID是否有效
                    JSONObject allNetworkEdgeIdValidObj = new JSONObject();
                    allNetworkNodeIdValidObjList.add(allNetworkNodeIdValidObj);
                    allNetworkEdgeIdValidObjList.add(allNetworkEdgeIdValidObj);
                    //无效的节点ID列表
                    List<String> notValidNetworkNodeIdArray = new ArrayList<>();
                    if(allNodeFeatures!=null && allNodeFeatures.size()>0){
                        for(int j=0;j<allNodeFeatures.size();j++){
                            JSONObject nodeFeature = allNodeFeatures.getJSONObject(j);
                            String nodeID = nodeFeature.getString("ID");
                            JSONArray nodeFieldNames = nodeFeature.getJSONArray("fieldNames");
                            JSONArray nodeFieldValues = nodeFeature.getJSONArray("fieldValues");
                            //获取节点是否有效
                            boolean tempValidBool = getValidBoolByType(nodeFieldNames,nodeFieldValues,typeList.get(i),pointList);//根据地震输入方式类型获取破坏状态，并获取有效、失效状态
                            if(tempValidBool==false){
                                notValidNetworkNodeIdArray.add(nodeID);
                            }
                        }
                    }
                    notValidNetworkNodeIdArrayList.add(notValidNetworkNodeIdArray);
                    //无效的弧段ID列表
                    List<String> notValidNetworkEdgeIdArray = new ArrayList<>();
                    if(allEdgeFeatures!=null && allEdgeFeatures.size()>0){
                        for(int j=0;j<allEdgeFeatures.size();j++){
                            JSONObject edgeFeature = allEdgeFeatures.getJSONObject(j);
                            String edgeID = edgeFeature.getString("ID");
                            JSONArray edgeFieldNames = edgeFeature.getJSONArray("fieldNames");
                            JSONArray edgeFieldValues = edgeFeature.getJSONArray("fieldValues");
                            //获取弧段是否有效
                            boolean tempValidBool = getValidBoolByType(edgeFieldNames,edgeFieldValues,typeList.get(i),lineList);//根据地震输入方式类型获取破坏状态，并获取有效、失效状态
                            if(tempValidBool==false){
                                notValidNetworkEdgeIdArray.add(edgeID);
                            }
                        }
                    }
                    notValidNetworkEdgeIdArrayList.add(notValidNetworkEdgeIdArray);
                }
                //查询源点的要素信息列表
                JSONArray sourceNodeFeatures = getSourceNodeFeatures(networkMapUrl,datasource,dataset);
                if(sourceNodeFeatures.size()>0){
                    for(int n=0;n<sourceNodeFeatures.size();n++){
                        JSONObject sourceNodeFeature = sourceNodeFeatures.getJSONObject(n);
                        String sourceNodeID = sourceNodeFeature.getString("ID");
                        JSONArray sourceNodeFieldNames = sourceNodeFeature.getJSONArray("fieldNames");
                        JSONArray sourceNodeFieldValues = sourceNodeFeature.getJSONArray("fieldValues");
                        if (PlatformObjectUtils.isEmpty(sourceNodeID)){
                            continue;
                        }
                        String nodeIDs = "["+sourceNodeID+"]";//源点节点ID
                        //连通性分析--不连通的弧段
                        JSONArray edgesFeaturesNotConnectResult = getNetworkConnectededges(networkUrl,nodeIDs,false);
                        //连通性分析--连通的弧段
                        JSONArray edgesFeaturesConnectResult = getNetworkConnectededges(networkUrl,nodeIDs,true);
                        //获取源点是否有效
                        boolean isValid = true;
                        for(int i=0;i<typeList.size();i++){
                            String type = typeList.get(i);
                            //获取源点是否有效
                            isValid = getValidBoolByType(sourceNodeFieldNames,sourceNodeFieldValues,type,pointList);//根据地震输入方式类型获取破坏状态，并获取有效、失效状态
                            //无效的节点ID列表
                            List<String> notValidNetworkNodeIdArray = notValidNetworkNodeIdArrayList.get(i);
                            //无效的弧段ID列表
                            List<String> notValidNetworkEdgeIdArray = notValidNetworkEdgeIdArrayList.get(i);
                            if(edgesFeaturesNotConnectResult.size()>0){
                                for(int j=0;j<edgesFeaturesNotConnectResult.size();j++){
                                    JSONObject edgesFeature = edgesFeaturesNotConnectResult.getJSONObject(j);
                                    JSONArray fieldValues = edgesFeature.getJSONArray("fieldValues");
                                    String smFNode = fieldValues.getString(4);
                                    String smTNode = fieldValues.getString(5);
                                    String smEdgeID = fieldValues.getString(6);
                                    //设置节点ID无效
                                    allNetworkNodeIdValidObjList.get(i).put(smFNode,false);
                                    allNetworkNodeIdValidObjList.get(i).put(smTNode,false);
                                    //设置弧段ID无效
                                    allNetworkEdgeIdValidObjList.get(i).put(smEdgeID,false);
                                }
                            }
                            //根据节点ID和已获取的弧段ID继续遍历连通性的弧段数组并获取新的弧段ID
                            JSONArray allEdgeIdObjArray = new JSONArray();
                            allEdgeIdObjArray = checkEdgesFeatures(edgesFeaturesConnectResult,sourceNodeID,allEdgeIdObjArray,isValid,notValidNetworkNodeIdArray,notValidNetworkEdgeIdArray);
                            if(allEdgeIdObjArray.size()>0){
                                for(int j=0;j<allEdgeIdObjArray.size();j++){
                                    JSONObject allEdgeIdObj = allEdgeIdObjArray.getJSONObject(j);
                                    JSONArray edgeIdObjArray = allEdgeIdObj.getJSONArray("edgeIdObjArray");
                                    for(int k=0;k<edgeIdObjArray.size();k++){
                                        JSONObject edgeIdObj = edgeIdObjArray.getJSONObject(k);
                                        String nodeId = edgeIdObj.getString("nodeId");
                                        String nextNodeId = edgeIdObj.getString("nextNodeId");
//                                        String smFNode = edgeIdObj.getString("smFNode");
//                                        String smTNode = edgeIdObj.getString("smTNode");
                                        String smEdgeID = edgeIdObj.getString("smEdgeID");
                                        boolean isValidBool = edgeIdObj.getBoolean("isValid");
                                        //只要存在1次有效则都有效
                                        if(isValidBool){//弧段及流入节点有效
                                            //设置弧段流入节点ID有效
                                            allNetworkNodeIdValidObjList.get(i).put(nodeId,true);
                                            if(notValidNetworkNodeIdArray.indexOf(nextNodeId)!=-1) {//弧段流出节点是否无效
                                                allNetworkNodeIdValidObjList.get(i).put(nextNodeId,false);
                                            }else{
                                                allNetworkNodeIdValidObjList.get(i).put(nextNodeId,true);
                                            }
                                            //设置弧段ID有效
                                            allNetworkEdgeIdValidObjList.get(i).put(smEdgeID,true);
                                        }else{
                                            //设置弧段流出节点ID无效
                                            if(!allNetworkNodeIdValidObjList.get(i).containsKey(nextNodeId)){
                                                allNetworkNodeIdValidObjList.get(i).put(nextNodeId,false);
                                            }
                                            if(!allNetworkNodeIdValidObjList.get(i).containsKey(nodeId)){
                                                if(notValidNetworkNodeIdArray.indexOf(nodeId)!=-1) {//弧段流入节点是否无效
                                                    allNetworkNodeIdValidObjList.get(i).put(nodeId,false);
                                                }else{
                                                    allNetworkNodeIdValidObjList.get(i).put(nodeId,true);
                                                }
                                            }
                                            //设置弧段ID无效
                                            if(!allNetworkEdgeIdValidObjList.get(i).containsKey(smEdgeID)){
                                                allNetworkEdgeIdValidObjList.get(i).put(smEdgeID,false);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                //根据地震输入方式的全部计算结果更新数据是否有效字段
                for(int i=0;i<typeList.size();i++){
                    String fieldName = null;
                    String type = typeList.get(i);
                    if(type.equals("地震影响场")){
                        fieldName = "functional_failure_correct";
                    }else if(type.equals("烈度6")){
                        fieldName = "functional_failure6_correct";
                    }else if(type.equals("烈度7")){
                        fieldName = "functional_failure7_correct";
                    }else if(type.equals("烈度8")){
                        fieldName = "functional_failure8_correct";
                    }else if(type.equals("烈度9")){
                        fieldName = "functional_failure9_correct";
                    }else if(type.equals("烈度10")){
                        fieldName = "functional_failure10_correct";
                    }
                    List<String> pointIdList1 = new ArrayList<>();//点数据有效的id列表
                    List<String> pointIdList2 = new ArrayList<>();//点数据失效的id列表
                    //地震输入方式的全部节点ID是否有效列表
                    JSONObject allNetworkNodeIdValidObj = allNetworkNodeIdValidObjList.get(i);
                    for(String nodeId : allNetworkNodeIdValidObj.keySet()){
                        boolean bool = allNetworkNodeIdValidObj.getBoolean(nodeId);
                        //主键id
                        String id = allNetworkNodeIdObj.getString(nodeId);
                        if(PlatformObjectUtils.isNotEmpty(id)){
                            if(bool){
                                pointIdList1.add(id);
                            }else{
                                pointIdList2.add(id);
                            }
                        }
                    }
                    //更新点数据的功能失效分析有效、失效状态
                    updateSmxEvaluationResults(pointIdList1, fieldName, "有效");
                    //更新点数据的功能失效分析有效、失效状态
                    updateSmxEvaluationResults(pointIdList2, fieldName, "失效");
                    List<String> lineIdList1 = new ArrayList<>();//点数据有效的id列表
                    List<String> lineIdList2 = new ArrayList<>();//点数据失效的id列表
                    //地震输入方式的全部弧段ID是否有效列表
                    JSONObject allNetworkEdgeIdValidObj = allNetworkEdgeIdValidObjList.get(i);
                    for(String edgeId : allNetworkEdgeIdValidObj.keySet()){
                        boolean bool = allNetworkEdgeIdValidObj.getBoolean(edgeId);
                        //主键id
                        String id = allNetworkEdgeIdObj.getString(edgeId);
                        if(PlatformObjectUtils.isNotEmpty(id)){
                            if(bool){
                                lineIdList1.add(id);
                            }else{
                                lineIdList2.add(id);
                            }
                        }
                    }
                    //更新线数据的功能失效分析有效、失效状态
                    updateSmxEvaluationResultsLine(lineIdList1, fieldName, "有效");
                    //更新线数据的功能失效分析有效、失效状态
                    updateSmxEvaluationResultsLine(lineIdList2, fieldName, "失效");
                }
                //异步刷新超图图层
                //超图刷新图层
                asyncService.asyncRefresh("fxqh_smx_evaluation_results");
                //超图刷新图层
                asyncService.asyncRefresh("fxqh_smx_evaluation_results_line");
            }else{
                return RestResponse.fail("请先导入网络拓扑数据");
            }
            return RestResponse.succeed("计算成功");
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail(e.getMessage());
        }
    }

    //查询源点的要素信息列表
    public JSONArray getSourceNodeFeatures(String networkMapUrl,String datasource,String dataset){
//        String layerUrl = iServerHttp + "/iserver/services/map-"+datasource+"/rest/maps/"+dataset+"@"+datasource;
//        String layerUrl = "http://10.7.208.233:8080/iserver/services/map-dxPipeNetwork/rest/maps/dxPipeNetwork_Network@dxPipeNetwork";
//        String layerUrl = "http://10.13.155.192:8090/iserver/services/map-smxNetwork/rest/maps/DataSource_Network@DataSource";
        String layerUrl = networkMapUrl;
        String networkType = "POINT";
        String sqlFilter = "NODETYPE = 1";//1源点
        JSONArray sourceNodeFeatures = new JSONArray();
        //查询源点
        RestResponse restResponse = mapSqlQueryResultsPost(layerUrl,datasource, dataset, networkType, sqlFilter);
        if(restResponse.getCode()==200){
            JSONObject result = (JSONObject) restResponse.getData();
            JSONArray recordsets = result.getJSONArray("recordsets");
            if(recordsets.size()>0){
                JSONObject recordset = recordsets.getJSONObject(0);
                JSONArray features = recordset.getJSONArray("features");
                if(features.size()>0){
                    sourceNodeFeatures = features;
                }
            }
        }
        return sourceNodeFeatures;
    }

    //查询全部点/线要素信息列表
    public JSONArray getAllFeaturesByNetworkType(String networkMapUrl,String datasource,String dataset,String networkType){
//        String layerUrl = iServerHttp + "/iserver/services/map-"+datasource+"/rest/maps/"+dataset+"@"+datasource;
//        String layerUrl = "http://10.7.208.233:8080/iserver/services/map-dxPipeNetwork/rest/maps/dxPipeNetwork_Network@dxPipeNetwork";
//        String layerUrl = "http://10.13.155.192:8090/iserver/services/map-smxNetwork/rest/maps/DataSource_Network@DataSource";
        String layerUrl = networkMapUrl;
//        String networkType = "POINT";
//        String networkType = "LINE";
        String sqlFilter = "1 = 1";//全部
        JSONArray allFeatures = new JSONArray();
        //查询
        RestResponse restResponse = mapSqlQueryResultsPost(layerUrl,datasource, dataset, networkType, sqlFilter);
        if(restResponse.getCode()==200){
            JSONObject result = (JSONObject) restResponse.getData();
            JSONArray recordsets = result.getJSONArray("recordsets");
            if(recordsets.size()>0){
                JSONObject recordset = recordsets.getJSONObject(0);
                JSONArray features = recordset.getJSONArray("features");
                if(features.size()>0){
                    allFeatures = features;
                }
            }
        }
        return allFeatures;
    }

    //连通性分析
    public JSONArray getNetworkConnectededges(String networkUrl,String nodeIDs,boolean connected){
        JSONArray edgesFeaturesResult = new JSONArray();
        //连通性分析
        RestResponse restResponse = networkConnectededges(networkUrl, nodeIDs, "", connected, true);
        if(restResponse.getCode()==200){
            JSONObject result = (JSONObject) restResponse.getData();
            JSONArray edgesFeatures = result.getJSONArray("edgesFeatures");
            if(edgesFeatures.size()>0){
                edgesFeaturesResult = edgesFeatures;
            }
        }

        return edgesFeaturesResult;
    }

    //根据节点ID和已获取的弧段ID继续遍历连通性的弧段数组并获取新的弧段ID
    public JSONArray checkEdgesFeatures(JSONArray edgesFeatures,String nodeId,JSONArray allEdgeIdObjArray,boolean isValid,List<String> notValidNetworkNodeIdArray,List<String> notValidNetworkEdgeIdArray){
        JSONArray edgeIdObjArray = new JSONArray();
        if(edgesFeatures!=null && edgesFeatures.size()>0){
            for(int i=0;i<edgesFeatures.size();i++){
                JSONObject edgesFeature = edgesFeatures.getJSONObject(i);
//                int ID = edgesFeature.getInteger("ID");
//                JSONArray fieldNames = edgesFeature.getJSONArray("fieldNames");
                JSONArray fieldValues = edgesFeature.getJSONArray("fieldValues");
                String smFNode = fieldValues.getString(4);
                String smTNode = fieldValues.getString(5);
                String smEdgeID = fieldValues.getString(6);
                String id = fieldValues.getString(9);//主键ID
                String type = edgesFeature.getString("type");//空间数据类型：POINT、LINE
                String nextNodeId = null;
                boolean edgeBool = false;
                if(smFNode.equals(nodeId) || smTNode.equals(nodeId)){
                    if(smFNode.equals(nodeId)){
                        nextNodeId = smTNode;
                    }else if(smTNode.equals(nodeId)){
                        nextNodeId = smFNode;
                    }
                    boolean tempValidBool = true;
                    if(isValid){
                        //判断是否无效的节点
                        if(notValidNetworkNodeIdArray.indexOf(nodeId)!=-1){//弧段流入节点
                            tempValidBool = false;
                        }
                        //判断是否无效的弧段
                        if(notValidNetworkEdgeIdArray.indexOf(smEdgeID)!=-1){
                            tempValidBool = false;
                        }
                    }else{
                        tempValidBool = false;
                    }
                    if(allEdgeIdObjArray.size()>0){//已有弧段计算数据
                        boolean bool = false;
                        for(int j=0;j<allEdgeIdObjArray.size();j++){
                            JSONObject allEdgeIdObj = allEdgeIdObjArray.getJSONObject(j);
                            JSONArray tempEdgeIdObjArray = allEdgeIdObj.getJSONArray("edgeIdObjArray");
                            for(int k=0;k<tempEdgeIdObjArray.size();k++){
                                JSONObject tempEdgeIdObj = tempEdgeIdObjArray.getJSONObject(k);
                                String tempEdgeId = tempEdgeIdObj.getString("smEdgeID");
                                if(tempEdgeId.equals(smEdgeID)){//此弧段已计算
                                    bool = true;
                                    break;
                                }
                            }
                            if(bool){
                                break;
                            }
                        }
                        if(bool==false){//只对未计算的弧段进行计算
                            edgeBool = true;
                        }
                    }else{
                        edgeBool = true;
                    }
                    if(edgeBool){
                        JSONObject edgeIdObj = new JSONObject();
                        edgeIdObj.put("nodeId",nodeId);
                        edgeIdObj.put("nextNodeId",nextNodeId);
                        edgeIdObj.put("smFNode",smFNode);
                        edgeIdObj.put("smTNode",smTNode);
                        edgeIdObj.put("smEdgeID",smEdgeID);
                        edgeIdObj.put("isValid",tempValidBool);
                        edgeIdObj.put("id",id);//主键ID
                        edgeIdObj.put("type",type);//空间数据类型：POINT、LINE
                        edgeIdObjArray.add(edgeIdObj);
                    }
                }
            }
        }
        JSONObject allEdgeIdObj = new JSONObject();
        allEdgeIdObj.put("nodeId",nodeId);
        allEdgeIdObj.put("edgeIdObjArray",edgeIdObjArray);
        allEdgeIdObjArray.add(allEdgeIdObj);
        if(edgeIdObjArray.size()>0){
            //获取下一节点弧段
            for (int i = 0; i < edgeIdObjArray.size(); i++) {
                JSONObject edgeIdObj = edgeIdObjArray.getJSONObject(i);
                String nextNodeId = edgeIdObj.getString("nextNodeId");//下一节点ID
                boolean vaildBool = edgeIdObj.getBoolean("isValid");//是否有效
                //根据节点ID和已获取的弧段ID继续遍历连通性的弧段数组并获取新的弧段ID
                allEdgeIdObjArray = checkEdgesFeatures(edgesFeatures,nextNodeId,allEdgeIdObjArray,vaildBool,notValidNetworkNodeIdArray,notValidNetworkEdgeIdArray);
            }
        }

        return allEdgeIdObjArray;
    }

    //根据字段名称获取数据
    public String getFieldValueByName(JSONArray fieldNames,JSONArray fieldValues,String name){
        String value = null;
        for(int i=0;i<fieldNames.size();i++){
            String fieldName = fieldNames.getString(i);
            if(fieldName.equals(name)){
                value = fieldValues.getString(i);//文本数据
                break;
            }
        }

        return value;
    }

    //判断网络分析服务是否为当前任务破坏等级分析，即判断主键ID是否存在一致
    public boolean getIdBoolByType(JSONArray allFeatures,List<EvaluationResults> list){
        boolean bool = false;

        if(allFeatures!=null && allFeatures.size()>0){
            for(int i=0;i<allFeatures.size();i++){
                JSONObject feature = allFeatures.getJSONObject(i);
                JSONArray fieldNames = feature.getJSONArray("fieldNames");
                JSONArray fieldValues = feature.getJSONArray("fieldValues");
                //根据字段名称获取数据
                String id = getFieldValueByName(fieldNames,fieldValues,"id");
                if (PlatformObjectUtils.isNotEmpty(id)) {//节点有主键id、弧段有主键id
                    for(EvaluationResults evaluationResults : list){
                        if(evaluationResults.getId().equals(id)){
                            bool = true;
                            break;
                        }
                    }
                }
            }
        }

        return bool;
    }

    //根据地震输入方式类型获取破坏状态，并获取有效、失效状态
    public boolean getValidBoolByType(JSONArray fieldNames,JSONArray fieldValues,String type,List<EvaluationResults> list){
        boolean bool = false;
        /*String fieldName = "";
        //超图字段截取数据库字段如下
        //"disaster_r","disaster_1","disaster_2","disaster_3","disaster_4","disaster_5","disaster_6","disaster_7","disaster_8","disaster_9","disaster10","disaster11"
        //"functional","function_1","function_2","function_3","function_4","function_5","function_6","function_7","function_8","function_9","function10","function11"
        if(type.equals("烈度6")){
//            fieldName = "disaster_rate6_state_correction";
            fieldName = "disaster_1";
        }else if(type.equals("烈度7")){
//            fieldName = "disaster_rate7_state_correction";
            fieldName = "disaster_3";
        }else if(type.equals("烈度8")){
//            fieldName = "disaster_rate8_state_correction";
            fieldName = "disaster_5";
        }else if(type.equals("烈度9")){
//            fieldName = "disaster_rate9_state_correction";
            fieldName = "disaster_7";
        }else if(type.equals("烈度10")){
//            fieldName = "disaster_rate10_state_correction";
            fieldName = "disaster_9";
        }else if(type.equals("地震影响场")){
//            fieldName = "disaster_rate_state_correction";
            fieldName = "disaster_11";
        }
        //根据字段名称获取数据
        String fieldValue = getFieldValueByName(fieldNames,fieldValues,fieldName);
        // 功能失效分析时，根据五个破坏状态，其中基本完好、轻微破坏和中等破坏为有效状态，严重破坏和毁坏为失效状态，有效状态为绿色，失效状态为红色
        if (PlatformObjectUtils.isNotEmpty(fieldValue)) {
            if(fieldValue.equals("基本完好") || fieldValue.equals("轻微破坏") || fieldValue.equals("中等破坏")){
                bool = true;
            }
        }
        */
        //根据字段名称获取数据
        String id = getFieldValueByName(fieldNames,fieldValues,"id");
        if (PlatformObjectUtils.isNotEmpty(id)) {//节点有主键id、弧段有主键id
            String fieldValue = null;
            for(EvaluationResults evaluationResults : list){
                if(evaluationResults.getId().equals(id)){
                    if(type.equals("烈度6")){
                        fieldValue = evaluationResults.getDisasterRate6StateCorrection();
                    }else if(type.equals("烈度7")){
                        fieldValue = evaluationResults.getDisasterRate7StateCorrection();
                    }else if(type.equals("烈度8")){
                        fieldValue = evaluationResults.getDisasterRate8StateCorrection();
                    }else if(type.equals("烈度9")){
                        fieldValue = evaluationResults.getDisasterRate9StateCorrection();
                    }else if(type.equals("烈度10")){
                        fieldValue = evaluationResults.getDisasterRate10StateCorrection();
                    }else if(type.equals("地震影响场")){
                        fieldValue = evaluationResults.getDisasterRateStateCorrection();
                    }
                    break;
                }
            }
            // 功能失效分析时，根据五个破坏状态，其中基本完好、轻微破坏和中等破坏为有效状态，严重破坏和毁坏为失效状态，有效状态为绿色，失效状态为红色
            if (PlatformObjectUtils.isNotEmpty(fieldValue)) {
                if(fieldValue.equals("基本完好") || fieldValue.equals("轻微破坏") || fieldValue.equals("中等破坏")){
                    bool = true;
                }
            }
        }else{//节点无主键id
            bool = true;
        }

        return bool;
    }

    //更新点数据的功能失效分析有效、失效状态
    public void updateSmxEvaluationResults(List<String> ids, String fieldName, String fieldValue) {
        if(ids!=null && ids.size()>0 && fieldName!=null){
            String fieldName0 = fieldName.split("_correct")[0];
            String sql = "update fxqh_smx_evaluation_results " +
                    "set "+fieldName0+"='"+fieldValue+"',"+fieldName+" = '" + fieldValue + "'  where id in (:ids)";
            Map map = new HashMap();
            map.put("ids", ids);
            namedParameterJdbcTemplate.update(sql, map);
        }
    }

    //更新线数据的功能失效分析有效、失效状态
    public void updateSmxEvaluationResultsLine(List<String> ids, String fieldName, String fieldValue) {
        if(ids!=null && ids.size()>0 && fieldName!=null){
            String fieldName0 = fieldName.split("_correct")[0];
            String sql = "update fxqh_smx_evaluation_results_line " +
                    "set "+fieldName0+"='"+fieldValue+"',"+fieldName+" = '" + fieldValue + "'  where id in (:ids)";
            Map map = new HashMap();
            map.put("ids", ids);
            namedParameterJdbcTemplate.update(sql, map);
        }
    }

    //查询生命线分析点、线数据的范围经纬度列表
    @Override
    public List<List<Double>> getSmxEvaluationResultExtentLonLatList(String taskId,String qcType){
        List<List<Double>> list = new ArrayList<>();
        //点数据
        String sql = "select st_extent(geom) from fxqh_smx_evaluation_results where task_id='"+taskId+"' and del_flag='0' ";
        //线数据
        String lineSql = "select st_extent(geom) from fxqh_smx_evaluation_results_line where task_id='"+taskId+"' and del_flag='0' ";
        if(qcType.equals("waterSupply")){//供水系统
            sql += "and (type=11 or type=2)";//11水厂泵房 2水厂水池
            lineSql += "and type=1";//1地下管网
        }else if(qcType.equals("gasSupply")){//供气系统
            sql += "and (type=3 or type=14)";//3燃气-储气罐 14燃气-门站/场站
            lineSql += "and type=15";//15供气管网
        }else if(qcType.equals("powerSupply")){//供电系统
            sql += "and (type=6 or type=12)";//6变电站 12重要发电厂房
            lineSql += "and type=8";//8电缆线路
        }else if(qcType.equals("traffic")){//交通系统
            sql += "and type=4";//4桥梁
            lineSql += "and (type=4 or type=5)";//4桥梁 5道路
        }else if(qcType.equals("communication")){//通信系统
            sql += "and type=4";//13通信基站 9通信室内设备
        }
        //查询范围经纬度列表
        list = queryExtentLonLatList(list,sql);
        //除通信系统
        if(!qcType.equals("communication")){
            //查询范围经纬度列表
            list = queryExtentLonLatList(list,lineSql);
        }

        return list;
    }

    //查询范围经纬度列表
    public List<List<Double>> queryExtentLonLatList(List<List<Double>> list,String sql){
        try {
            String extent = jdbcTemplate.queryForObject(sql, String.class);
            //获取范围经纬度列表
            List<List<Double>> lonlatList = getExtentLonLatList(extent);
            if(lonlatList.size()==2){
                list.add(lonlatList.get(0));
                list.add(lonlatList.get(1));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;
    }

    //获取范围经纬度列表
    public List<List<Double>> getExtentLonLatList(String extent){
        List<List<Double>> list = new ArrayList<>();
        if(!PlatformObjectUtils.isEmpty(extent) && extent.startsWith("BOX(")){
            extent = extent.replace("BOX(","").replace(")","");
            String[] temp = extent.split(",");
            //左下角经纬度
            List<Double> lonlat = new ArrayList<>();
            String[] lonlatStr = temp[0].split(" ");
            double lon = Double.valueOf(lonlatStr[0]);
            double lat = Double.valueOf(lonlatStr[1]);
            lonlat.add(lon);
            lonlat.add(lat);
            list.add(lonlat);
            //右上角经纬度
            List<Double> lonlat1 = new ArrayList<>();
            String[] lonlatStr1 = temp[1].split(" ");
            double lon1 = Double.valueOf(lonlatStr1[0]);
            double lat1 = Double.valueOf(lonlatStr1[1]);
            lonlat1.add(lon1);
            lonlat1.add(lat1);
            list.add(lonlat1);
        }

        return list;
    }
}

